package com.dlc.video;

import android.content.Context;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ADView extends LinearLayout {

    private List<String> imgList = new ArrayList<>();

    private List<String> videoList = new ArrayList<>();

    private Banner mBanner;

    private MyVideoView myVideoView;

    private ImageView mIvDefault;

    private int duration = 5000;

    private Context mContext;

    private Handler mHandler = new Handler();

    private ADViewClickListener mADViewClickListener;

    private ImageView.ScaleType imageScaleType = ImageView.ScaleType.FIT_XY;

    public ADView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        this.mContext = context;

        // 加载布局
        LayoutInflater.from(context).inflate(R.layout.ad_layout, this);

        mBanner = (Banner) findViewById(R.id.banner);

        myVideoView = (MyVideoView) findViewById(R.id.videoview);

        mIvDefault = (ImageView) findViewById(R.id.iv_default);
        mBanner.setViewPagerIsScroll(false);
    }

    private boolean isStop;
    private int selectPosition;

    public void setDefaultImg(int res) {
        mIvDefault.setImageResource(res);
    }

    public void setmADViewClickListener(ADViewClickListener mADViewClickListener) {
        this.mADViewClickListener = mADViewClickListener;
    }

    public void setImgList(List<String> imgList) {
        if (!(this.imgList.containsAll(imgList) && imgList.containsAll(this.imgList))) {
            this.imgList = imgList;
            mBanner.setImages(imgList).setDelayTime(duration).setImageLoader(new GlideImageLoader()).setBannerStyle(BannerConfig.NOT_INDICATOR);
        }
    }

    public void setVideoList(List<String> videoList) {
        this.videoList = videoList;
        isStop = false;
        //        try {
        //            deleteContents(mContext.getExternalFilesDir("download_video"));
        //        } catch (IOException e) {
        //            e.printStackTrace();
        //        }
    }


    public void deleteContents(File dir) throws IOException {
        File[] files = dir.listFiles();
        if (files == null) {
            throw new IOException("not a readable directory: " + dir);
        }
        List<String> strings = new ArrayList<>();
        for (String s : videoList) {
            String fileName = s.substring(s.lastIndexOf("/") + 1);
            strings.add(fileName);
        }
        for (File file : files) {
            if (file.isDirectory()) {
                deleteContents(file);
            }
            if (!strings.contains(file.getName())) {
                if (!file.delete()) {
                    throw new IOException("failed to delete file: " + file);
                }
            }
        }
    }

    public void setDuration(int duration) {
        if (duration < 3000) {
            duration = 3000;
        }
        this.duration = duration;
        mBanner.setDelayTime(duration);
    }

    private void initView() {

        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if (mADViewClickListener != null) mADViewClickListener.onCLick(position);
            }
        });

        mBanner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                selectPosition = position;
                if (position >= (imgList.size() - 1)) {
                    if (videoList.size() != 0) {
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mBanner.stopAutoPlay();
                            }
                        }, duration - 1000);
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Log.e(")))))))))))", isStop + "===");
                                if (!isStop) {
                                    mBanner.setVisibility(View.GONE);
                                    myVideoView.setVisibility(View.VISIBLE);
                                    myVideoView.setList(videoList);
                                }
                            }
                        }, duration);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        myVideoView.setVideoStateListener(new MyVideoView.VideoStateListener() {
            @Override
            public void playEnd() {
                mBanner.setVisibility(View.VISIBLE);
                myVideoView.setVisibility(View.GONE);
                mBanner.start();
            }
        });
    }

    /**
     * 开始播放
     */
    public void start() {
        initView();
        myVideoView.suspend();//视频回收
        if (imgList.size() != 0) {
            mBanner.start();
            myVideoView.setAutoStop(true);
            mBanner.setVisibility(View.VISIBLE);
            myVideoView.setVisibility(View.GONE);
            mIvDefault.setVisibility(GONE);
        } else if (videoList.size() != 0) {
            myVideoView.setAutoStop(false);
            myVideoView.setList(videoList);
            mBanner.setVisibility(View.GONE);
            myVideoView.setVisibility(View.VISIBLE);
            mIvDefault.setVisibility(GONE);
        } else {
            mBanner.setVisibility(View.GONE);
            myVideoView.setVisibility(View.GONE);
        }
    }

    private class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(final Context context, Object path, final ImageView imageView) {
            imageView.setScaleType(imageScaleType);
            GlideApp.with(context)
                    .load(path)
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .apply(new RequestOptions().placeholder(R.drawable.img_banner_default)
                    .error(getResources().getDrawable(R.drawable.img_banner_default)))
                    .into(imageView);
        }
    }

    public void pause() {
        isStop = true;
        mBanner.stopAutoPlay();
        myVideoView.stopPlayback();
    }

    public void resume() {
        isStop = false;
        if (selectPosition >= (imgList.size() - 1) && !videoList.isEmpty()) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (!isStop) {
                        mBanner.setVisibility(View.GONE);
                        myVideoView.setVisibility(View.VISIBLE);
                        myVideoView.start();
                        //myVideoView.setList(videoList);
                    }
                }
            }, duration);
        } else {
            mBanner.startAutoPlay();
        }
    }

    public void destory() {
        mHandler.removeCallbacksAndMessages(null);
        myVideoView.stopPlayback();
    }

    public interface ADViewClickListener {
        void onCLick(int position);
    }

    public void setScaleType(ImageView.ScaleType scaleType) {
        this.imageScaleType = scaleType;
    }

    public ImageView.ScaleType getScaleType() {
        return this.imageScaleType;
    }
}
